<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>微服务-CAP理论 | 若愚湖畔</title><meta name="keywords" content="微服务,分布式"><meta name="author" content="albafica"><meta name="copyright" content="albafica"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="CAP理论名词解释 C: consistency 一致性，保持所有节点在同一时刻有相同的、逻辑一致的数据 A: availability 可用性，保证每个请求不管成功、失败都有响应 P: partition tolerance 分区容忍性，系统中丢失的任何信息或失败，都不会影响系统的继续运行  详细说明CAP定理是Eric Brewer教授在2000年提出的,该原则指出，任何分布式系统都不可能同时">
<meta property="og:type" content="article">
<meta property="og:title" content="微服务-CAP理论">
<meta property="og:url" content="https://albafica.gitee.io/2022/05/07/cap/index.html">
<meta property="og:site_name" content="若愚湖畔">
<meta property="og:description" content="CAP理论名词解释 C: consistency 一致性，保持所有节点在同一时刻有相同的、逻辑一致的数据 A: availability 可用性，保证每个请求不管成功、失败都有响应 P: partition tolerance 分区容忍性，系统中丢失的任何信息或失败，都不会影响系统的继续运行  详细说明CAP定理是Eric Brewer教授在2000年提出的,该原则指出，任何分布式系统都不可能同时">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="">
<meta property="article:published_time" content="2022-05-07T01:12:07.000Z">
<meta property="article:modified_time" content="2022-05-07T02:00:26.231Z">
<meta property="article:author" content="albafica">
<meta property="article:tag" content="微服务">
<meta property="article:tag" content="分布式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content=""><link rel="shortcut icon" href="/hexoblog/img/favicon.png"><link rel="canonical" href="https://albafica.gitee.io/2022/05/07/cap/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/hexoblog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexoblog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '微服务-CAP理论',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-07 10:00:26'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.1.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s1.ax1x.com/2022/04/23/Lhpz3F.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/hexoblog/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="data-item"><a href="/hexoblog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="data-item"><a href="/hexoblog/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexoblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexoblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/hexoblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexoblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexoblog/">若愚湖畔</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexoblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexoblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/hexoblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexoblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">微服务-CAP理论</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-05-07T01:12:07.000Z" title="发表于 2022-05-07 09:12:07">2022-05-07</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-07T02:00:26.231Z" title="更新于 2022-05-07 10:00:26">2022-05-07</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">977</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>2分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="CAP理论"><a href="#CAP理论" class="headerlink" title="CAP理论"></a>CAP理论</h1><h2 id="名词解释"><a href="#名词解释" class="headerlink" title="名词解释"></a>名词解释</h2><ul>
<li>C: consistency 一致性，保持所有节点在同一时刻有相同的、逻辑一致的数据</li>
<li>A: availability 可用性，保证每个请求不管成功、失败都有响应</li>
<li>P: partition tolerance 分区容忍性，系统中丢失的任何信息或失败，都不会影响系统的继续运行</li>
</ul>
<h2 id="详细说明"><a href="#详细说明" class="headerlink" title="详细说明"></a>详细说明</h2><p>CAP定理是Eric Brewer教授在2000年提出的,该原则指出，任何分布式系统都不可能同时满足这三个特点。所以在设计时，满足其中两个即可。</p>
<ul>
<li>CA: 满足一致性和可用性。 缺点在于扩展性不好。</li>
<li>CP: 满足一致性和分区容忍性。 缺点是性能一般不好。</li>
<li>AP: 满足可用性和分区容忍性。 缺点是数据一致性问题不太好。</li>
</ul>
<h2 id="个人理解"><a href="#个人理解" class="headerlink" title="个人理解"></a>个人理解</h2><h3 id="一致性"><a href="#一致性" class="headerlink" title="一致性"></a>一致性</h3><p>一致性的意思就是用户更新数据后，无论哪个节点获取到的数据都是最新的。因为微服务化后，数据散落在不同的数据库中，要做到强一致性，需要把所有节点中的数据都同步更新，这个性能是会很差的。而如果使用同一个业务数据库，那就不是分布式了，最终压力还是集中到了那一两个节点上。</p>
<h3 id="可用性"><a href="#可用性" class="headerlink" title="可用性"></a>可用性</h3><p>我对可用性的理解就是某一个微服务整体挂掉了，整个业务链路并不会阻塞，要么直接返回错误给用户，比如最近上海一直在抢菜，大家对抢不到菜是有预期的，库存服务压力很大，很容易崩溃，这时候你不能让用户一点下单等了半天服务器超时返回系统繁忙，能提前抛出一个重试的提示，用户体验度完全不一样的。</p>
<h3 id="分区容忍性"><a href="#分区容忍性" class="headerlink" title="分区容忍性"></a>分区容忍性</h3><p>单体应用下，服务一挂就全挂，但只需要运维一个服务，复杂程度要低很多。而到了分布式系统上，一个大应用被拆分成了数个小服务，因为网络、存储等各方面因素都会导致服务的不可用，所以运维压力也大大增加，这边所谓的可用性就是指其中某一个节点宕机了不会影响到整个链路上。解决方案就是避免出现单点节点，比如数据库有主从，单服务也有多个节点冗余。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>目前除非一些金融系统等对数据强一致性有极高要求，一般的互联网应用，对性能要求更高。在这种情况下，数据一致性如果能通过其他手段实现数据的最终一致性，那么追求AP是更好的选择。</p>
<p>举例来说，用户下载简历扣减费用，逻辑上可能涉及到简历管理+下载数管理两个微服务，先在下载数管理服务中扣减下载数成功，然后调用到简历管理模块是，因为异常简历管理模块下发简历失败，只要能让用户已经扣减的下载数还原回去，那这一次失败就是可容忍的。</p>
<p>同类的就是烂大街的电商业务，库存扣减了，但扣费失败，库存还回去就行。</p>
<p>我个人理解，微服务更多还是解决业务系统庞大到一定程度后，关联方太多引出的开发效率降低、沟通成本变高的问题。毕竟一个单体上线一堆功能，就算编译都要半天，还会引起各种冲突。所以微服务的目标是高可用，更白话的说法就是让99%的用户感觉快跟重要。</p>
<p>所以，微服务主要追求高可用和分区容忍性，轻一致性。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">albafica</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://albafica.gitee.io/2022/05/07/cap/">https://albafica.gitee.io/2022/05/07/cap/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://albafica.gitee.io" target="_blank">若愚湖畔</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexoblog/tags/%E5%BE%AE%E6%9C%8D%E5%8A%A1/">微服务</a><a class="post-meta__tags" href="/hexoblog/tags/%E5%88%86%E5%B8%83%E5%BC%8F/">分布式</a></div><div class="post_share"></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://s1.ax1x.com/2022/04/23/Lhpz3F.png" onerror="this.onerror=null;this.src='/hexoblog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">albafica</div><div class="author-info__description">Stay hungry Stay foolish</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/hexoblog/archives/"><div class="headline">文章</div><div class="length-num">11</div></a></div><div class="card-info-data-item"><a href="/hexoblog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="card-info-data-item"><a href="/hexoblog/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#CAP%E7%90%86%E8%AE%BA"><span class="toc-number">1.</span> <span class="toc-text">CAP理论</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%8D%E8%AF%8D%E8%A7%A3%E9%87%8A"><span class="toc-number">1.1.</span> <span class="toc-text">名词解释</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%A6%E7%BB%86%E8%AF%B4%E6%98%8E"><span class="toc-number">1.2.</span> <span class="toc-text">详细说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AA%E4%BA%BA%E7%90%86%E8%A7%A3"><span class="toc-number">1.3.</span> <span class="toc-text">个人理解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E8%87%B4%E6%80%A7"><span class="toc-number">1.3.1.</span> <span class="toc-text">一致性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%AF%E7%94%A8%E6%80%A7"><span class="toc-number">1.3.2.</span> <span class="toc-text">可用性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E5%8C%BA%E5%AE%B9%E5%BF%8D%E6%80%A7"><span class="toc-number">1.3.3.</span> <span class="toc-text">分区容忍性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">1.3.4.</span> <span class="toc-text">总结</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/18/techupdate/" title="技术升级简要构思">技术升级简要构思</a><time datetime="2022-05-18T12:54:43.000Z" title="发表于 2022-05-18 20:54:43">2022-05-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/07/functionalinterface/" title="Function接口简单代码结构">Function接口简单代码结构</a><time datetime="2022-05-07T10:18:48.000Z" title="发表于 2022-05-07 18:18:48">2022-05-07</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/07/cap/" title="微服务-CAP理论">微服务-CAP理论</a><time datetime="2022-05-07T01:12:07.000Z" title="发表于 2022-05-07 09:12:07">2022-05-07</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/02/optional/" title="optional的使用">optional的使用</a><time datetime="2022-05-02T02:10:03.000Z" title="发表于 2022-05-02 10:10:03">2022-05-02</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/hexoblog/2022/05/01/pattern-overload/" title="设计模式-概述">设计模式-概述</a><time datetime="2022-05-01T10:12:20.000Z" title="发表于 2022-05-01 18:12:20">2022-05-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By albafica</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/hexoblog/js/utils.js"></script><script src="/hexoblog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="富强,民主,文明,和谐,爱国,敬业,诚信,友善" data-fontsize="15px" data-random="false" async="async"></script></div></body></html>